$(document).ready(function () {
    // 棋谱
    var chessManual = [];
    var currStep = [-1, 2];
    var getCurrentStep = function () {
        return chessManual[currStep[0]][currStep[1]];
    }
    //当前焦点
    var currPos = "";
    //当前玩家
    var currPlayer = 0  //0红 1黑 2结束
    //总路径;
    var chessPath = [];
    // 棋盘
    var chessBorad = $('.chess-board');
    //  车 马 相(象) 士  帅(将) 炮 兵(卒) 
    var chessManStr = ['r', 'n', 'b', 'a', 'k', 'c', 'p'];

    //红 黑 0 1
    var chessColor = ['r', 'b'];
    var blackInit = {
        '00': [1, 0], '10': [1, 1], '20': [1, 2], '30': [1, 3],
        '40': [1, 4], '50': [1, 3], '60': [1, 2], '70': [1, 1],
        '80': [1, 0], '12': [1, 5], '72': [1, 5], '03': [1, 6],
        '23': [1, 6], '43': [1, 6], '63': [1, 6], '83': [1, 6]
    };
    var redInit = {
        '09': [0, 0], '19': [0, 1], '29': [0, 2], '39': [0, 3],
        '49': [0, 4], '59': [0, 3], '69': [0, 2], '79': [0, 1],
        '89': [0, 0], '17': [0, 5], '77': [0, 5], '06': [0, 6],
        '26': [0, 6], '46': [0, 6], '66': [0, 6], '86': [0, 6]
    };
    var blackPlayer = {};
    var redPlayer = {};
    //转换
    var Pos2Key = function (pos) {
        return pos[0] + '' + pos[1];
    }
    var Key2Pos = function (str) {
        return str.split('').map(function (item, index, array) {
            return parseInt(item);
        })
    }

    // 棋子
    var chessMan = function (ck, position) {
        // 节点
        this.node = $('<figure></figure>');
        // 坐标
        this.position = position;
        // 颜色
        this.color = ck[0];
        //种类
        this.kind = ck[1];
        // 标记
        this.Checked = false;
        //图片
        this.img = '';
        // 路径
        this.path = []  //{key,kill};

    }
    // 初始化
    chessMan.prototype.init = function () {
        //添加到棋盘
        this.node.appendTo(chessBorad);
        // 显示
        this.addPath();
        this.show();
    }

    // 添加行棋路径
    chessMan.prototype.addPath = function (k) {
        this.path.push({ key: Pos2Key(this.position), kill: k })
    }
    //坐标转换函数
    var Pos2Offset = function (pos) {
        return [pos[0] * 40 + 6, pos[1] * 40 + 6];
    }
    // 显示
    chessMan.prototype.show = function () {
        var left = Pos2Offset(this.position)[0];
        var top = Pos2Offset(this.position)[1];
        var s = '';
        if (this.Checked) {
            s = 's';
        } else {
            s = '';
        }
        var img = 'url(./img/wood/' + chessColor[this.color] + chessManStr[this.kind] + s + '.gif' + ')';
        this.node.css({ "backgroundImage": img, "left": left, "top": top });
    }
    chessMan.prototype.hide = function () {
        this.node.hide();
    }
    //移动
    chessMan.prototype.moveBy = function (offset, callback) {
        this.Checked = 1;
        this.show();
        this.position[0] += offset[0];
        this.position[1] += offset[1];
        var left = Pos2Offset(this.position)[0];
        var top = Pos2Offset(this.position)[1];
        this.node.addClass('frunt');
        this.node.animate({ left: left, top: top }, callback);
    }

    //移动到
    chessMan.prototype.moveTo = function (pos, callback) {
        this.Checked = 1;
        this.show();
        this.position = pos;
        var left = Pos2Offset(pos)[0];
        var top = Pos2Offset(pos)[1];
        this.node.addClass('frunt');
        this.node.animate({ left: left, top: top }, callback);
    }

    var manualTable = $('#manual-steps');//棋谱文字
    // 解析棋谱
    var parseManual = function (str) {
        var temp = str.split('\n');
        chessManual = temp.map(function (item, index, array) {
            return $.trim(item).split(' ');
        });
        chessManual.forEach(function (item, index, array) {
            var tr = $("<div class='col-xs-4 column'></div>").appendTo(manualTable);
            $('<span>' + item[0] + '</span>').appendTo(tr);
            $('<span>&nbsp;</span>').appendTo(tr);
            $('<span>' + item[1] + '</span>').addClass('has-border-red').appendTo(tr);
            $('<span>&nbsp;</span>').appendTo(tr);
            $('<span>' + item[2] + '</span>').addClass('has-border-black').appendTo(tr);
        })
    }
    var showCurrentStep = function () {
        // $('#manual-steps')
        if (currStep[0] == -1) {
            $('#manual-steps .column').children('span').removeClass('font-bold');
            return;
        }
        var sp = $('#manual-steps .column').eq(currStep[0]).children('span');
        if (currStep[1] == 1) {
            $('#manual-steps .column').children('span').removeClass('font-bold');   //siblings
            sp.eq(2).addClass('font-bold');
        } else if (currStep[1] = 2) {
            $('#manual-steps .column').children('span').removeClass('font-bold');    //siblings
            sp.eq(4).addClass('font-bold');
        }

    }
    // 解析走法
    var chessManKey = {
        '车': 0, '马': 1, '相': 2, '象': 2, '士': 3, '仕': 3, '将': 4, '帅': 4,
        '炮': 5, '砲': 5, '兵': 6, '卒': 6
    }
    var stepKey = {
        '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9
    }
    var stepKey2 = {
        '１': 1, '２': 2, '３': 3, '４': 4, '５': 5, '６': 6, '７': 7, '８': 8, '９': 9
    }
    // 焦点清除
    var clearTarget = function () {

        if (currPlayer == 0 && redPlayer.hasOwnProperty(currPos)) {
            redPlayer[currPos].Checked = false;
            redPlayer[currPos].node.removeClass('frunt');
            redPlayer[currPos].show();
        }
        if (currPlayer == 1 && blackPlayer.hasOwnProperty(currPos)) {
            blackPlayer[currPos].Checked = false;
            blackPlayer[currPos].node.removeClass('frunt');
            blackPlayer[currPos].show();
        }
    }
    //棋子移动和数据处理
    function moveByAndCom(man, x, y) {
        clearTarget();
        var key1 = Pos2Key(man.position);
        var key2 = Pos2Key([man.position[0] + x, man.position[1] + y]);
        //console.log(key2);
        if (man.color == 0) {
            // 如果移动的位置有对方棋子
            if (blackPlayer.hasOwnProperty(key2)) {
                //console.log('吃')
                man.addPath(blackPlayer[key2]);
                man.moveBy([x, y], function () {
                    blackPlayer[key2].hide.call(blackPlayer[key2]);
                    delete blackPlayer[key2];
                    nextEnable=true;
                });

            } else {
                man.addPath();
                man.moveBy([x, y],function(){
                    nextEnable=true;
                });
            }
            //console.log(man.position);

            redPlayer[key2] = man;
            delete redPlayer[key1];
            currPos = key2;
            currPlayer = 0;
        } else if (man.color == 1) {
            if (redPlayer.hasOwnProperty(key2)) {
                //console.log(redPlayer[key2]);
                man.addPath(redPlayer[key2]);
                man.moveBy([x, y], function () {
                    redPlayer[key2].hide.call(redPlayer[key2]);
                    delete redPlayer[key2];
                    nextEnable=true;
                });

            } else {
                man.addPath();
                man.moveBy([x, y],function(){
                    nextEnable=true;
                });
            }
            blackPlayer[key2] = man;
            delete blackPlayer[key1];
            currPos = key2;
            currPlayer = 1;
        }
        chessPath.push([currPlayer, currPos]);
    }
    var parseStep = function (str) {
        var temp = str.split('');
        var s1 = temp[0];
        var s2 = temp[1];
        var s3 = temp[2];
        var s4 = temp[3];
        //查找棋子
        var man;
        //第一个字是否是棋子
        if (chessManKey.hasOwnProperty(s1)) {
            // 红
            if (stepKey.hasOwnProperty(s4)) {

                for (key in redPlayer) {
                    var red_p = redPlayer[key];
                    if (chessManKey[s1] == red_p.kind && 8 - red_p.position[0] == stepKey[s2] - 1) {
                        man = red_p;
                        break;
                    }
                }
            }
            //黑
            else {
                for (key in blackPlayer) {
                    var black_p = blackPlayer[key];
                    if (chessManKey[s1] == black_p.kind && black_p.position[0] == stepKey2[s2] - 1) {
                        man = black_p;
                        break;
                    }
                }
            }
        }
        else {
            // 红黑
            if (stepKey.hasOwnProperty(s4)) {
                var manlist = [];
                for (key in redPlayer) {
                    var red_p = redPlayer[key];
                    if (chessManKey[s2] == red_p.kind) {
                        manlist.push(red_p);
                    }
                }
                if (s1 == '前') {
                    if (manlist[0].position[1] < manlist[1].position[1]) {
                        man = manlist[0];
                    } else {
                        man = manlist[1]
                    }
                } else if (s1 == '后') {
                    if (manlist[0].position[1] < manlist[1].position[1]) {
                        man = manlist[1];
                    } else {
                        man = manlist[0]
                    }
                }
            } else {
                var manlist = [];
                for (key in blackPlayer) {
                    var black_p = blackPlayer[key];
                    if (chessManKey[s2] == black_p.kind) {
                        manlist.push(black_p);
                    }
                }
                if (s1 == '前') {
                    if (manlist[0].position[1] > manlist[1].position[1]) {
                        man = manlist[0];
                    } else {
                        man = manlist[1]
                    }
                } else if (s1 == '后') {
                    if (manlist[0].position[1] > manlist[1].position[1]) {
                        man = manlist[1];
                    } else {
                        man = manlist[0]
                    }
                }
            }

        }

        if (!man) {
            alert('找不到相关棋子');
            return;
        }
        // 行走
        var offsetX;
        var offsetY;
        var BY
        if (man.color == 0) {
            offsetX = 9 - stepKey[s4] - man.position[0];
            offsetY = -stepKey[s4];
            BY = -1;
        } else {
            offsetX = stepKey2[s4] - man.position[0] - 1;
            offsetY = stepKey2[s4];
            BY = 1;
        }


        if (s3 == '平') {
            moveByAndCom(man, offsetX, 0);
            //man.moveBy([offsetX, 0]);
        } else if (s3 == '进') {
            //马
            if (man.kind == 1) {
                if (Math.abs(offsetX) == 1) {
                    //man.moveBy([offsetX, 2 * BY]);
                    moveByAndCom(man, offsetX, 2 * BY);
                } else {
                    moveByAndCom(man, offsetX, 1 * BY);
                }
            }
            //相
            else if (man.kind == 2) {
                moveByAndCom(man, offsetX, 2 * BY);
            }
            //士
            else if (man.kind == 3) {
                moveByAndCom(man, offsetX, 1 * BY);
            }
            //其他直走的
            else {
                moveByAndCom(man, 0, offsetY);
            }
        } else if (s3 == '退') {
            //马
            if (man.kind == 1) {
                if (Math.abs(offsetX) == 1) {
                    moveByAndCom(man, offsetX, -2 * BY);
                } else {
                    moveByAndCom(man, offsetX, -1 * BY);
                }
            }
            //相
            else if (man.kind == 2) {
                moveByAndCom(man, offsetX, -2 * BY);
            }
            //士
            else if (man.kind == 3) {
                moveByAndCom(man, offsetX, -1 * BY);
            }
            //其他直走的
            else {
                moveByAndCom(man, 0, -offsetY);
            }
        }

    }
    $("#submitManual").on('click', function (event) {
        chessBorad.html('');
        manualTable.html('');
        ManualInit();
        parseManual($('#manual-input').val());
    });
    $("#btn-prev").on('click', function (event) {
        if (chessPath.length == 0) {
            //当前玩家
            currPlayer = 0  //0红 1黑 2结束
            currStep = [-1, 2];
            alert('已经回到初始阶段');
            return;
        }

        var man;
        var path = chessPath.pop();
        if (path[0] == 0) {
            man = redPlayer[path[1]];
        } else {
            man = blackPlayer[path[1]];
        }

        var pre = man.path[man.path.length - 1];

        if (pre.kill) {
            if (currPlayer == 0) {
                blackPlayer[path[1]] = pre.kill;
            } else {
                redPlayer[path[1]] = pre.kill;
            }
            pre.kill.node.show();
        }

        // 上一个焦点显示
        if (chessPath.length != 0) {
            var man2;
            var path2 = chessPath[chessPath.length - 1];
            if (path2[0] == 0) {
                man2 = redPlayer[path2[1]];
            } else {
                man2 = blackPlayer[path2[1]];
            }
            man2.Checked = true;
            man2.show();
        }
        man.moveTo(Key2Pos(pre.key));
        man.Checked = false;
        man.node.removeClass('frunt');
        man.show();
        man.path.pop();
        if (path[0] == 0) {
            redPlayer[pre.key] = man;
            delete redPlayer[path[1]];
            currPos = pre.key;
            currPlayer = 1  //0红 1黑 2结束
        } else {
            blackPlayer[pre.key] = man;
            delete blackPlayer[path[1]];
            currPos = pre.key;
            //当前玩家
            currPlayer = 0  //0红 1黑 2结束
        }
        if (currStep[1] == 2) {
            currStep[1] = 1;

        } else {
            currStep[0] -= 1;
            currStep[1] = 2;

        }
        showCurrentStep();
    });
    // 点击状态
    var nextEnable = true;
    //下一步按钮
    $("#btn-next").on('click', function (event) {
        if (nextEnable) {
            nextEnable=false;
            if (currStep[1] == 1) {
                currStep[1] = 2
            }
            else if (currStep[1] == 2 && currStep[0] < chessManual.length - 1) {
                currStep[0] += 1;
                currStep[1] = 1;
            } else if (currStep[1] == 2 && currStep[0] == chessManual.length - 1) {
                alert('已经最后一步了');
                nextEnable=true;
                return;
            }
            var step = getCurrentStep();
            parseStep(step);
            showCurrentStep();

        }else{
            alert('您慢点点，数据处理跟不上(ノへ￣、)');
        }
    });
    var ManualInit = function () {
        redPlayer = {};
        blackPlayer = {};
        chessManual = [];
        currStep = [-1, 2];
        //当前焦点
        currPos = "";
        //当前玩家
        currPlayer = 0  //0红 1黑 2结束
        //总路径;
        chessPath = [];
        for (key in redInit) {
            var man = new chessMan(redInit[key], Key2Pos(key));
            man.init();
            redPlayer[key] = man;
        }
        for (key in blackInit) {
            var man = new chessMan(blackInit[key], Key2Pos(key));
            man.init();
            blackPlayer[key] = man;
        }
    }
    ManualInit();
})